#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "ohos_init.h"       // OpenHarmony初始化相关
#include "cmsis_os2.h"       // CMSIS-RTOS2接口
#include "hi_wifi_api.h"     // HiSilicon WiFi API
#include "lwip/netifapi.h"   // LWIP网络接口API
#include "lwip/ip4_addr.h"   // IPv4地址处理

// WiFi配置 - 请修改为你的热点信息
#define WIFI_SSID "TEST01"       // 要连接的WiFi热点名称
#define WIFI_PASSWORD "12345678" // WiFi密码
#define WIFI_IFNAME_LEN 16       // 网络接口名称最大长度

// WiFi连接状态
static int g_wifi_connected = 0;         // WiFi连接状态标志
static char g_connected_ssid[33] = {0};  // 已连接的SSID存储

// WiFi事件回调函数
static void wifi_connect_callback(const hi_wifi_event *event)
{
    if (event == NULL) {
        return;
    }

    switch (event->event) {
        case HI_WIFI_EVT_SCAN_DONE:
            printf("[WiFi] Scan completed\n");
            break;
            
        case HI_WIFI_EVT_CONNECTED:
            printf("[WiFi] Connected successfully\n");
            strncpy(g_connected_ssid, WIFI_SSID, sizeof(g_connected_ssid) - 1);
            g_wifi_connected = 1;
            break;
            
        case HI_WIFI_EVT_DISCONNECTED:
            printf("[WiFi] Disconnected\n");
            g_wifi_connected = 0;
            memset(g_connected_ssid, 0, sizeof(g_connected_ssid));
            break;
            
        default:
            printf("[WiFi] Event: %d\n", event->event);
            break;
    }
}

// WiFi连接函数
static int wifi_connect_to_hotspot(void)
{
    int ret;
    char ifname[WIFI_IFNAME_LEN] = {0};
    int len = WIFI_IFNAME_LEN;
    
    printf("[WiFi] Starting WiFi connection...\n");
    
    // 1. 注册WiFi事件回调
    ret = hi_wifi_register_event_callback(wifi_connect_callback);
    if (ret != HISI_OK) {
        printf("[WiFi] Failed to register callback: %d\n", ret);
        return ret;
    }
    
    // 2. 启动STA模式
    ret = hi_wifi_sta_start(ifname, &len);
    if (ret != HISI_OK) {
        printf("[WiFi] Failed to start STA: %d\n", ret);
        return ret;
    }
    printf("[WiFi] STA started, interface: %s\n", ifname);
    
    // 3. 扫描附近热点
    printf("[WiFi] Scanning for hotspots...\n");
    ret = hi_wifi_sta_scan();
    if (ret != HISI_OK) {
        printf("[WiFi] Failed to start scan: %d\n", ret);
        return ret;
    }
    
    // 等待扫描完成
    sleep(3);
    
    // 4. 配置连接参数
    hi_wifi_assoc_request assoc_req = {0};
    
    // 设置SSID
    int ssid_len = strlen(WIFI_SSID);
    if (ssid_len > 32) {  // Hi3861 最大SSID长度
        printf("[WiFi] SSID too long\n");
        return -1;
    }
    memcpy(assoc_req.ssid, WIFI_SSID, ssid_len);
    
    // 设置密码
    int pwd_len = strlen(WIFI_PASSWORD);
    if (pwd_len > 64) {  // Hi3861 最大密码长度
        printf("[WiFi] Password too long\n");
        return -1;
    }
    memcpy(assoc_req.key, WIFI_PASSWORD, pwd_len);
    
    // 设置加密方式
    assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;
    
    // 5. 连接热点
    printf("[WiFi] Connecting to: %s\n", WIFI_SSID);
    ret = hi_wifi_sta_connect(&assoc_req);
    if (ret != HISI_OK) {
        printf("[WiFi] Failed to connect: %d\n", ret);
        return ret;
    }
    
    // 等待连接结果
    int timeout = 30;
    while (timeout > 0 && !g_wifi_connected) {
        sleep(1);
        timeout--;
        if (timeout % 5 == 0) {  // 每5秒打印一次状态
            printf("[WiFi] Waiting for connection... %d seconds left\n", timeout);
        }
    }
    
    if (g_wifi_connected) {
        printf("[WiFi] Successfully connected to: %s\n", g_connected_ssid);
        
        // 获取并显示IP地址信息
        struct netif *netif = netifapi_netif_find(ifname);
        if (netif != NULL) {
            // printf("[WiFi] IP Address: %s\n", ip4addr_ntoa(&netif->ip_addr.u_addr.ip4));
            // printf("[WiFi] Gateway: %s\n", ip4addr_ntoa(&netif->gw.u_addr.ip4));
            // printf("[WiFi] Netmask: %s\n", ip4addr_ntoa(&netif->netmask.u_addr.ip4));
        }
        return 0;
    } else {
        printf("[WiFi] Connection timeout\n");
        return -1;
    }
}

// WiFi连接任务
static void WiFiConnectTask(void *arg)
{
    (void)arg;
    
    // 等待系统初始化完成
    sleep(2);
    
    while (1) {
        if (!g_wifi_connected) {
            printf("[WiFi] Attempting to connect to hotspot...\n");
            int ret = wifi_connect_to_hotspot();
            
            if (ret != 0) {
                printf("[WiFi] Connection failed, retry in 10 seconds\n");
                sleep(10);
            } else {
                printf("[WiFi] Connection successful!\n");
                printf("[WiFi] ========== WiFi Status ==========\n");
                printf("[WiFi] Status: Connected\n");
                printf("[WiFi] SSID: %s\n", g_connected_ssid);
                printf("[WiFi] ================================\n");
            }
        } else {
            // 已连接，每5秒检查一次连接状态
            sleep(5);
            printf("[WiFi] Status Check: Connected to %s\n", g_connected_ssid);
        }
    }
}

void WiFiDemo(void)
{
    printf("[WiFi] WiFi Demo Starting...\n");
    
    // 创建WiFi连接任务
    osThreadAttr_t wifi_attr = {
        .name = "WiFiConnectTask",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U,
        .stack_mem = NULL,
        .stack_size = 2048,  // 减少栈大小以节省内存
        .priority = osPriorityNormal,
    };

    if (osThreadNew((osThreadFunc_t)WiFiConnectTask, NULL, &wifi_attr) == NULL) {
        printf("[WiFi] Failed to create WiFi connect task!\n");
    } else {
        printf("[WiFi] WiFi connect task created successfully!\n");
    }
}

SYS_RUN(WiFiDemo);